<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JS实现的数字过渡动画</title>
    <style>
        .demo-1 {
            width: 60%;
            margin: 50px auto;
        }
        #show {
            color: #d7ab4c;
            font-weight: bold;
            font-size: 24px;
            font-family: 'Courier New', Courier, monospace;
        }
    </style>
</head>
<body>
    <div class="demo-1">
        <h2>JS实现的数字过渡动画</h2>
        <p id="show-dl" ></p>
        <button onclick="doTest()" >show</button>
    </div>
    <script>
        function numberAnimation ({from, to, duration=1000, callback}) {
            let val = from;
            const startTime = Date.now();
            const speed = (to - from) / duration;
            const myDone = function () {
                const time = Date.now() - startTime;
                if (time >= duration) {
                    //超过指定动画时间
                    val = to;
                    callback && callback(val);
                    return;
                }

                val = from + time * speed;
                callback && callback(val);
                requestAnimationFrame(myDone);
            }

            myDone();
        }
        let showEle = document.querySelector('#show-dl');
        let from = 1000;
        showEle.innerText = from.toFixed(2);
        //测试
        function doTest() {
            numberAnimation({
                from: from,
                to: 899,
                duration: 3000,
                callback: function(newVal){
                    showEle.innerText = newVal.toFixed(2);
                }
            });
        }
    </script>
</body>
</html>